package com.tem.interceptor;


import com.tem.utils.StringUtil;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.Map;

/**
 * @Author: tiger
 * @Date:2018/5/5
 * @Description:
 */
public class MyInterceptor implements HandlerInterceptor {
    /**
     * 日志记录器
     */
    private final Logger logger = Logger.getLogger(MyInterceptor.class);

    /**
     * @Author:Tiger
     * @Date:2018/5/19 10:43
     * @Params:
     * @Returns:
     * @Description: 进入方法之前
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Long startTime = System.currentTimeMillis();
        request.setAttribute("startTime", startTime);

        StringBuffer requestURL = request.getRequestURL();
        logger.info("【请求路径】" + requestURL + ",【请求IP】" + getIpAddress(request));

        // 请求参数
        StringBuilder logger = new StringBuilder("【请求参数】");
        Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String paramName = parameterNames.nextElement();
            String param = (String) request.getParameter(paramName);
            logger.append("[" + paramName + "] = [" + param + "];");
        }

        // 日志打印
        String loggerStr = logger.toString();
        if (loggerStr.contains(",")) {
            loggerStr = loggerStr.substring(0, loggerStr.length() - 1);
        }
        this.logger.info(loggerStr);
        return true;
    }

    /**
     * @Author:Tiger
     * @Date:2018/5/19 10:43
     * @Params:
     * @Returns:
     * @Description: preHandle方法的返回值为true 时才能被调用, controller方法结束但视图返回渲染之前被调用。
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        StringBuilder logger = new StringBuilder("【返回参数】");
//        Map<String, Object> model = modelAndView.getModel();
//
//        for (String key : model.keySet()) {
//            logger.append(key + "=" + model.get(key) + ",");
//        }
//
//        String loggerStr = logger.toString();
//        if (loggerStr.contains(",")) {
//            loggerStr = loggerStr.substring(0, loggerStr.length() - 1);
//        }

//        this.logger.info(loggerStr);
    }

    /**
     * @Author:Tiger
     * @Date:2018/5/19 10:43
     * @Params:
     * @Returns:
     * @Description: preHandle方法的返回值为true 时才能被调用, 在DispatcherServlet 渲染了对应的视图之后执行。
     * 这个方法的主要作用是用于进行资源清理工作的。
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        Long startTime = (Long) request.getAttribute("startTime");
        Long endTime = System.currentTimeMillis();
        Long ElapsedTime = endTime - startTime;

        logger.info("【请求路径】" + request.getRequestURL() + ",【耗时】" + ElapsedTime + "ms");
    }

    /**
     * @Author:Tiger
     * @Date:2018/5/19 15:53
     * @Params:
     * @Returns:
     * @Description: 获取Ip地址
     * 1.获取用户真实IP地址，不使用request.getRemoteAddr();的原因是有可能用户使用了代理软件方式避免真实IP地址。
     * 可是，如果通过了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP值，究竟哪个才是真正的用户端的真实IP呢？
     * 答案是取X-Forwarded-For中第一个非unknown的有效IP字符串。
     */
    private String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
